package com.gsdse.service.impl;

import com.gsdse.pojo.ReturnData;
import com.gsdse.service.SendEmailService;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.net.HttpURLConnection;
import java.util.Date;
import java.util.Properties;

@Service
public class SendEmailServiceImpl implements SendEmailService {

    /**
     * 以下为静态初始化
     */
    private static int sendCount = 0;

     private static int account_index=0;

//    //发邮箱账号数组，防止同一个账号一天发送上限（测试用的）
//    private static String []accountArray={"wlyfb1@163.com","wlyfb2@163.com","wlyfb3@163.com"};
//    //三个月后需要重新授权
//    private static String []passwordArray={"XBHTMTLCFRFANRYN","FURVNKIKHXXYEUEY","CAWFXKKHCRKJQDBL"};
     //发邮箱账号数组，防止同一个账号一天发送上限
    private static String []accountArray={"GSD_KJ@163.com","gs_kj1@163.com","gs_kj2@163.com","mengchu0907@163.com","mengchu2024@163.com","wlyfb1@163.com","wlyfb2@163.com","wlyfb3@163.com","GSD_KJ3@163.com"};
    //三个月后需要重新授权
    private static String []passwordArray={"WIZJGGMSIGKXYHYA","MXZKKSYHGCVFUSVX","EUJEWVUOTNUWMUVG","RKGCDMJMTFGPHOPP","LNMIAYYOFUBDTFWY","XBHTMTLCFRFANRYN","FURVNKIKHXXYEUEY","CAWFXKKHCRKJQDBL","XOYUDJUQJSVBSLCB"};

    // 发件人的 邮箱 和 密码（替换为自己的邮箱和密码）
    static String myEmailAccount = "GSD_KJ3@163.com";
    // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性，给 SMTP 客户端设置了独立密码（有的邮箱称为“授权码”）,
    //     对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码（授权码）。
    static String myEmailPassword = "XOYUDJUQJSVBSLCB";

    // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
    //如；163邮箱是smtp.163.com，qq邮箱是smtp.qq.com。
    static String myEmailSMTPHost = "smtp.163.com";
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置
    // 参数配置类
    static Properties props = new Properties();

    //邮件的署名
    static String SENDEMAILAUTHOR = "广师大科教";

    final static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    static {
        // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.transport.protocol", "smtp");
        // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.host", myEmailSMTPHost);
        // 需要请求认证
        props.setProperty("mail.smtp.auth", "true");
        //阿里云服务器禁用25端口，需使用465端口 服了找一晚上原来就是你个阿里搞的鬼
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    }


    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session     和服务器交互的会话对象
     * @param sendMail    发件人邮箱
     * @param toUser      收件人
     * @return
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, String  toUser, String emailSubject, String emailContent) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人（昵称有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改昵称）
        message.setFrom(new InternetAddress(sendMail, SENDEMAILAUTHOR, "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
//        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));

        // 设置多个收件人地址
        if(null != toUser && !toUser.isEmpty()){
            @SuppressWarnings("static-access")
            InternetAddress[] internetAddressTo = new InternetAddress().parse(toUser);
            message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
        }


        // 4. Subject: 邮件主题
        message.setSubject(emailSubject, "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(emailContent, "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }


    @Override
    public ReturnData sendWxchangeDutyEmail(String toUser, String a, String title) throws Exception {

        // 1. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getInstance(props);
        // 设置为debug模式, 可以查看详细的发送 log
        //session.setDebug(true);
        // 2. 创建一封邮件即邮件对象
        String emailContent = a;
        MimeMessage message = createMimeMessage(session, myEmailAccount, toUser, title, emailContent);

        // 3. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport();

        // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错

        transport.connect(myEmailAccount, myEmailPassword);

        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());

        // 7. 关闭连接
        transport.close();
        ReturnData re = new ReturnData();
        re.setMsg("发送成功");
        re.setData(HttpURLConnection.HTTP_OK);
        re.setCode(1);

        ++sendCount;
        if(sendCount % 5 == 0){
            sendCount=0;
            //9为数组邮箱数量
            account_index=((account_index+1)%9);
            myEmailAccount=accountArray[account_index];
            myEmailPassword=passwordArray[account_index];
        }
        return re;
    }

    public ReturnData sendPicEmail(String toUser, String title, String content, String departmentId) throws Exception {
        Session session = Session.getInstance(props);

        //session.setDebug(true);

        MimeMessage message = createEmailMessageWithPic(session, myEmailAccount, toUser, title, content,departmentId);

        Transport transport = session.getTransport();

        transport.connect(myEmailAccount, myEmailPassword);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        ReturnData re = new ReturnData();
        re.setMsg("发送成功");
        re.setData(HttpURLConnection.HTTP_OK);
        re.setCode(1);

        ++sendCount;
        if(sendCount % 5 == 0){
            sendCount=0;
            //9为数组邮箱数量
            account_index=((account_index+1)%9);
            myEmailAccount=accountArray[account_index];
            myEmailPassword=passwordArray[account_index];
        }
        return re;

    }

    //发送含图片的
    public static MimeMessage createEmailMessageWithPic(Session session, String sendMail, String toUser, String title, String emailContent,String departmentId) throws Exception {

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(sendMail, SENDEMAILAUTHOR, "UTF-8"));

        if(null != toUser && !toUser.isEmpty()){
            @SuppressWarnings("static-access")
            InternetAddress[] internetAddressTo = new InternetAddress().parse(toUser);
            message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
        }

        MimeMultipart mimeMultipart = new MimeMultipart();

        message.setSubject(title, "UTF-8");



        MimeBodyPart img=new MimeBodyPart();
        //注意文件访问路径(图片需要按部门ID命名且图片格式为jpg)"/usr/local/src/pic/"
        DataHandler dataHandler = new DataHandler(new FileDataSource("/usr/local/src/pic/"+departmentId+".jpg"));
        img.setDataHandler(dataHandler);
        img.setFileName("面试群.jpg");
        img.setContentID("img");
        mimeMultipart.addBodyPart(img);

        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<img style=\"max-width: 350px; max-height: 600px;\" src='cid:img'/>"+"<div style=\"font-size: 35px;\">"+emailContent+"</div>", "text/html;charset=UTF-8");
        mimeMultipart.addBodyPart(text);

        mimeMultipart.setSubType("related");
        message.setContent(mimeMultipart);
        message.setSentDate(new Date());

        return message;
    }
}
